<script setup lang="ts">
import $ from 'jquery';
import { ref, defineOptions, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import axios from 'axios'
// import { getChapter } from '@/api/getAxios2.ts'
defineOptions({
    name: "reading",
})
const $router = useRouter()
const route = useRoute()
const props = defineProps(['chapterNum', "chapter", 'backColor', 'aboutFont'])
const emit = defineEmits(["changeToFlag", "changeTitle", "next", "pre", "changeNowPage", "changeAllPages"])
const content: any = ref([])

//是用于判断是否为第一页，可不可以翻到上一章
let flagForFirst = ref(false);
//用于判断是否为最后一页，可不可以翻到下一章
let flagForLast = ref(false);
//记录当前章节的res
const resData = ref({})
//一开始获取数据
function getData(chapterId: string) {

    axios.get("m1/storyChapter/content?chapterId=" + chapterId)
        .then((res: any) => {
            resData.value = res
            changeContent(res);
            let str2 = ''
            content.value.forEach((item: any) => {
                str2 += `<div class='page1'>${item}</div>`
            })
            $("#book").html(str2);
            nextTick(() => {
                $('#book').turn({
                    acceleration: true, //好像是给手机端的一个加速模式什么的
                    display: "single",  //double双页模式，single单页模式
                    // page: 1, //默认第几页
                    duration: 200,// 翻页的速度 默认200
                    gradients: true, //折叠处的阴影效果，默认是true
                    when: {
                        turned: function (e:any, page:any) {
                            e;
                            //翻页完成时就会触发，刚开始时也触发一次
                            //page为当前的页数
                            emit('changeToFlag')
                            emit("changeNowPage", page)
                            if (page == $("#book").turn("pages") && $("#book").turn("pages") != 1) {
                                flagForLast.value = true
                            } else if (page === 1) {
                                flagForFirst.value = true;
                            } else {
                                flagForFirst.value = false;
                                flagForLast.value = false;
                            }
                        }
                    },
                })
                //一开始的所有页数
                emit("changeAllPages", $("#book").turn("pages") * 1)

            })
        })
}
getData(props.chapterNum);
//获取res然后对content进行更改
const changeContent = (res: any) => {
    content.value = []
    // console.log(res.data.data)
    let arr = res.data.data.split("\n\n\n");

    // let newStr = str.replace(/\s/g, ''); 
    // console.log(arr)
    let title = arr[0]  //标题
    emit("changeTitle", title)
    let resContent1 = arr[1].split("\n") //本章内容
    let resContent = resContent1.map((o: any) => o.replace(/\s/g, ''))
    // let last = arr[2]     //作者的话

    let first = "<div class='title1'>" + title + "</div>"
    /** 
     * 先定死行数和列数，列数:15.行数:17
     */
    let str = '<div class="page1"><div class="padding1">' + first    //记录当前页面
    let max = props.aboutFont.xNum * props.aboutFont.yNum;  //最大存储的字数    15行每行15字
    let nowFont = 0;    //记录当前的字数
    let tempFont = 0;
    for (let i = 0; i < resContent.length; i++) {
        let now = resContent[i].length + 2
        tempFont = now % props.aboutFont.xNum === 0 ? now : now + (props.aboutFont.xNum - now % props.aboutFont.xNum)
        if (tempFont + nowFont < max) {
            nowFont += tempFont
            str += `<p>${resContent[i]}</p>`
        } else if (tempFont + nowFont === max) {
            str += `<div>${resContent[i]}</div></div></div>`
            content.value.push(str)
            str = '<div class="page1"><div class="padding1">'
            nowFont = 0
        } else if (tempFont + nowFont > max) {
            /**
             * 此部分为扣掉那些超出去的字体，但是有BUG，还没完全写好
             * 
             */
            // let a = max - nowFont
            // let pre = resContent[i].slice(0, max - nowFont + 30)
            // let after = resContent[i].slice(max - nowFont + 30)
            // str += `<div>${pre}</div></div></div>`
            // content.value.push(str)
            // str = `<div class='page1'><div class="padding1"><div class='last1'>${after}</div>`
            // nowFont = after.length % props.aboutFont.xNum === 0 ? after.length : after.length + (15 - after.length % 15)

            /**
             * 此部分与 === 相同
             */
            str += `<div>${resContent[i]}</div></div></div>`
            content.value.push(str)
            str = '<div class="page1"><div class="padding1">'
            nowFont = 0


        }
        // console.log(nowFont, max)
    }
}
// 111
/**
 * watch路由参数
 */
watch(() => route.query, (nVal: any) => {
    let target = nVal.target ? nVal.target : 0;
    // $("#book").turn("removepage",1)
    let pageNum = $("#book").turn("pages") * 1
    axios.get("m1/storyChapter/content?chapterId=" + props.chapter[target].id)
        .then((res: any) => {
            resData.value = res
            changeContent(res)
            content.value.forEach((item: any) => {
                $("#book").turn("addPage", item, $("#book").turn("pages") * 1 + 1)
            })
            while (pageNum > 0) {
                pageNum--;
                $("#book").turn("removePage", 1);
            }
            //更新所有页数
            emit("changeAllPages", $("#book").turn("pages") * 1)
            if (nVal.flag === '1') {
                $("#book").turn("page", $("#book").turn("pages") * 1)
                flagForLast.value = true
                flagForFirst.value = false
            } else {
                $("#book").turn("page", 1)
                flagForLast.value = false
                flagForFirst.value = true
            }
        })

}, { deep: true })

//点击左右翻页
const fn = (e: { clientX: number; }) => {
    let tarRight = window.innerWidth * 4 / 5
    let tarLeft = window.innerWidth * 1 / 5
    if (e.clientX >= tarRight) {
        if (flagForLast.value) {
            emit("next", flagForLast.value)
            flagForLast.value = false
        } else {
            $("#book").turn("next")
        }
    } else if (e.clientX <= tarLeft) {
        if (flagForFirst.value) {
            flagForFirst.value = false
            emit("pre")
        } else {
            $("#book").turn("previous")
        }
    }
}
/**
 * watch字体大小
 */
watch(props.aboutFont, () => {
    console.log("现在大小->>", props.aboutFont.xNum)
    // $("#book").turn("resize")
    let nowPage = $("#book").turn("page") * 1

    let pageNum = $("#book").turn("pages") * 1
    changeContent(resData.value)
    content.value.forEach((item: any) => {
        $("#book").turn("addPage", item, $("#book").turn("pages") * 1 + 1)
    })
    while (pageNum > 0) {
        pageNum--;
        $("#book").turn("removePage", 1);
    }
    if (nowPage > $("#book").turn("page") * 1) {
        nowPage = $("#book").turn("page") * 1
    }
    $("#book").turn("page", nowPage)
    // emit("changeAllPages", $("#book").turn("pages") * 1)
    // if (nVal.flag === '1') {
    //     $("#book").turn("page", $("#book").turn("pages") * 1)
    //     flagForLast.value = true
    //     flagForFirst.value = false
    // } else {
    //     flagForLast.value = false
    //     flagForFirst.value = true
    // }

}, { deep: true })
//         $("#book").turn("previous")
//     }
// }

/**
 * 阅读记录
 **/
// 监听路由变化
watch(() => $router.currentRoute.value,
    (newValue: any) => {
        let speed = JSON.parse(<any>localStorage.getItem("speed"))
        //本地无该书籍进度
        if (speed.findIndex((val: { id: any }) => val.id == newValue.query.id) == -1) {
            let data = [{ id: newValue.query.id, target: newValue.query.target }, ...speed]
            //向本地保存该书籍进度
            localStorage.setItem("speed", JSON.stringify(data))
        } else {
            //本地已有该书籍进度
            speed.splice(speed.findIndex((val: { id: any }) => val.id == newValue.query.id), 1)
            let data = [{ id: newValue.query.id, target: newValue.query.target }, ...speed]
            localStorage.setItem("speed", JSON.stringify(data))
        }
    },
    { immediate: true }
)

</script>
<template>
    <div id="bookBox">

        <div id="book" @click="fn" :class="backColor"
            :style="`font-size: ${aboutFont.maxX / (aboutFont.xNum + 1)}px;text-indent: ${aboutFont.maxX / (aboutFont.xNum + 1) * 2}px;`">
            <!-- <div class="page1" v-for="item in content" :key="Math.random() + ''" v-html="item"></div> -->
        </div>
        <div :class="`bottomBox ${backColor}`"
            :style="(aboutFont.xNum === 13 || aboutFont.xNum === 12 || aboutFont.xNum === 17 || aboutFont.xNum === 22 ? 'height:11vw;' : '') ||
                (aboutFont.xNum === 11 || aboutFont.xNum === 16 || aboutFont.xNum === 21 || aboutFont.xNum === 26 ? 'height:7vw;' : '')">

        </div>
    </div>
</template>

<style scoped lang='less'>
#bookBox {
    width: 100vw;
    height: 100vh;
    position: relative;

    .bottomBox {
        position: fixed;
        // background-color: blue;
        width: 100%;
        height: 9vw;
        bottom: 0;
        left: 0;
        z-index: 29;
    }

    .eaeaea {
        background-color: #eaeaea !important;
    }

    .d7c3b8 {
        background-color: #d7c3b8 !important;
    }

    .d8ddea {
        background-color: #d8ddea !important;
    }

    .f2e4cb {
        background-color: #f2e4cb !important;
    }

    .black {
        background-color: #2d2a28 !important;
        color: white !important;
    }
}
</style>
<style lang="less">
#book {
    width: 100vw;
    height: 100vh;
    position: absolute;
    top: 0;
    -webkit-font-smoothing: antialiased;
    font-family: "微软雅黑";
    /* font-size: 1.5rem; */
    /* text-indent: 3rem; */

    .page1 {
        z-index: 3;
        overflow: hidden;
        backface-visibility: hidden;
        position: relative;
        background-color: white;


        .title1 {
            // color: red !important;
            font-weight: bold;
            text-indent: 0;
        }

        .last1 {
            text-indent: 0;
        }

        .padding1 {
            /* padding: 1vw; */
            padding: 2rem;
            line-height: 2em;
        }
    }

}

.eaeaea .page1 {
    background-color: #eaeaea !important;
}

.d7c3b8 .page1 {
    background-color: #d7c3b8 !important;
}

.d8ddea .page1 {
    background-color: #d8ddea !important;
}

.f2e4cb .page1 {
    background-color: #f2e4cb !important;
}

.black .page1 {
    background-color: #2d2a28 !important;
    color: white !important;
}
</style>